<template>
	<view class="container">
		<view class="form-section">
			<text class="section-title">编辑规则内容</text>
			<text class="section-desc">请编辑以下信息，更新裁判规则内容</text>
			
			<view class="form-item">
				<text class="form-label required">规则标题</text>
				<input class="form-input" type="text" v-model="formData.title" placeholder="请输入规则标题" />
			</view>
			
			<view class="form-item">
				<text class="form-label required">规则内容</text>
				<view class="textarea-container">
					<textarea class="form-textarea" v-model="formData.content" placeholder="请输入规则详细内容（支持Markdown格式）" maxlength="-1" />
				</view>
			</view>
			
			<!-- 文档和图片上传 -->
			<view class="form-item">
				<text class="form-label">文档和图片上传</text>
				<view class="upload-container">
					<view class="upload-box" @click="chooseDocument" v-if="!formData.document_url">
						<text class="upload-icon">📄</text>
						<text class="upload-text">点击选择文档</text>
					</view>
					<button 
						class="upload-button" 
						type="primary" 
						@click="chooseDocument" 
						v-if="!formData.document_url">
						选择文档
					</button>
					<view class="upload-preview" v-if="formData.document_url">
						<text class="preview-name">{{ documentName }}</text>
						<view class="preview-actions">
							<button class="preview-btn play-btn" @click="previewDocument">预览</button>
							<button class="preview-btn delete-btn" @click="removeDocument">删除</button>
						</view>
					</view>
					<text class="upload-tip">支持pdf、doc、docx格式，大小不超过10MB</text>
				</view>
				<view class="upload-container">
					<view class="upload-box" @click="chooseImage" v-if="!formData.image_url">
						<text class="upload-icon">🖼️</text>
						<text class="upload-text">点击选择图片</text>
					</view>
					<button 
						class="upload-button" 
						type="primary" 
						@click="chooseImage" 
						v-if="!formData.image_url">
						选择图片
					</button>
					<view class="image-preview" v-if="formData.image_url">
						<image class="preview-image" :src="formData.image_url" mode="aspectFill"></image>
						<view class="image-actions">
							<button class="image-btn play-btn" @click="previewImage">预览</button>
							<button class="image-btn delete-btn" @click="removeImage">删除</button>
						</view>
					</view>
					<text class="upload-tip">建议尺寸16:9，格式为jpg、png</text>
				</view>
			</view>
			
			<view class="form-item">
				<text class="form-label required">规则摘要</text>
				<input class="form-input" type="text" v-model="formData.summary" placeholder="请输入简短摘要，不超过200字" />
			</view>
			
			<view class="form-item">
				<text class="form-label required">规则分类</text>
				<picker class="form-picker" :value="categoryIndex" :range="categoryOptions" @change="bindCategoryChange">
					<view class="picker-value">
						{{ categoryOptions[categoryIndex] }}
					</view>
				</picker>
			</view>
			
			<view class="form-item">
				<text class="form-label required">规则标签</text>
				<input class="form-input" type="text" v-model="formData.tags" placeholder="请输入标签，多个标签用逗号分隔" />
			</view>
			
			<view class="form-item">
				<text class="form-label required">规则版本</text>
				<input class="form-input" type="text" v-model="formData.version" placeholder="请输入规则版本，如2023/24" />
			</view>
			
			<view class="form-item">
				<text class="form-label required">语言</text>
				<picker class="form-picker" :value="languageIndex" :range="languageOptions" @change="bindLanguageChange">
					<view class="picker-value">
						{{ languageOptions[languageIndex] }}
					</view>
				</picker>
			</view>
			
			<view class="form-item">
				<text class="form-label">状态</text>
				<picker class="form-picker" :value="statusIndex" :range="statusOptions" @change="bindStatusChange">
					<view class="picker-value">
						{{ statusOptions[statusIndex] }}
					</view>
				</picker>
			</view>
		</view>
		
		<view class="submit-section">
			<button class="submit-btn" @click="submitForm" :disabled="submitting">{{ submitting ? '更新中...' : '更新规则' }}</button>
		</view>
	</view>
</template>

<script>
	import '../admin/app.css';
	import { getToken } from '../../utils/tokenManager.js';
	
	export default {
		data() {
			return {
				ruleId: '',
				userInfo: null,
				userId: '',
				formData: {
					title: '',
					content: '',
					summary: '',
					category: '比赛规则',
					tags: '',
					version: '',
					language: 'zh-CN',
					document_url: '',
					image_url: '',
					status: 'published'
				},
				categoryOptions: ['比赛规则', '裁判指南', '技术指导', '其他'],
				categoryIndex: 0,
				languageOptions: ['中文(zh-CN)', '英文(en)'],
				languageIndex: 0,
				statusOptions: ['已发布', '草稿'],
				statusIndex: 0,
				submitting: false,
				documentName: '',
				uploadStatus: {
					document: false,
					image: false
				},
				loading: true
			}
		},
		onLoad(options) {
			if (options.id) {
				this.ruleId = options.id;
				console.log('编辑规则ID:', this.ruleId);
			} else {
				this.handleError('未指定规则ID');
				return;
			}
			
			// 获取用户信息并加载规则数据
			this.getUserInfo();
		},
		methods: {
			// 获取用户信息
			getUserInfo() {
				const userInfoStr = uni.getStorageSync('userInfo');
				if (userInfoStr) {
					try {
						let userInfo = JSON.parse(userInfoStr);
						
						// 确保userInfo对象包含_id字段
						if (!userInfo._id && userInfo.userId) {
							userInfo._id = userInfo.userId;
							// 更新存储
							uni.setStorageSync('userInfo', JSON.stringify(userInfo));
						}
						
						this.userInfo = userInfo;
						this.userId = userInfo._id || userInfo.userId || '';
						console.log('已获取登录用户信息:', this.userInfo);
						
						// 加载规则详情
						this.loadRuleDetail();
					} catch (e) {
						console.error('解析用户信息失败', e);
						this.userInfo = null;
						this.handleError('获取用户信息失败');
					}
				} else {
					console.log('本地无用户信息，尝试从云端获取');
					this.getUserInfoFromCloud();
				}
			},
			
			// 从云端获取用户信息
			async getUserInfoFromCloud() {
				uni.showLoading({
					title: '加载中...'
				});
				
									try {
						const userService = uniCloud.importObject('user-service');
						const res = await userService.getUserInfo(getToken());
					
					uni.hideLoading();
					
					if (res.code === 0 && res.data) {
						// 完整保存用户信息，确保包含_id字段
						this.userInfo = {
							...res.data,
							_id: res.data.userId
						};
						this.userId = this.userInfo._id;
						uni.setStorageSync('userInfo', JSON.stringify(this.userInfo));
						
						// 加载规则详情
						this.loadRuleDetail();
					} else {
						this.handleError('获取用户信息失败');
					}
				} catch (err) {
					uni.hideLoading();
					console.error('调用获取用户信息云对象失败', err);
					this.handleError('网络错误，请重试');
				}
			},
			
			// 加载规则详情
			async loadRuleDetail() {
				uni.showLoading({
					title: '加载中...'
				});
				
				try {
					const learningService = uniCloud.importObject('learning-service');
					const res = await learningService.getRuleDetail({
						id: this.ruleId
					});
					
					uni.hideLoading();
					this.loading = false;
					
					if (res.code === 0 && res.data) {
						const ruleData = res.data;
						
						// 检查是否为当前用户发布的规则
						if (this.userId && (this.userId !== ruleData.creator_id && this.userId !== ruleData.author_id)) {
							this.handleError('您无权编辑此规则');
							return;
						}
						
						// 填充表单数据
						this.formData = {
							title: ruleData.title || '',
							content: ruleData.content || '',
							summary: ruleData.summary || '',
							category: ruleData.category || '比赛规则',
							tags: Array.isArray(ruleData.tags) ? ruleData.tags.join(',') : ruleData.tags || '',
							version: ruleData.version || '',
							language: ruleData.language || 'zh-CN',
							document_url: ruleData.document_url || '',
							image_url: ruleData.image_url || '',
							status: ruleData.status || 'published'
						};
						
						// 设置正确的选择器索引
						this.categoryIndex = this.categoryOptions.indexOf(this.formData.category);
						if (this.categoryIndex === -1) this.categoryIndex = 0;
						
						this.languageIndex = this.formData.language === 'en' ? 1 : 0;
						
						this.statusIndex = this.formData.status === 'draft' ? 1 : 0;
						
						// 如果有文档，获取文档名称
						if (this.formData.document_url) {
							this.documentName = this.getFileNameFromUrl(this.formData.document_url);
						}
						
						console.log('已加载规则详情:', this.formData);
					} else {
						this.handleError('获取规则详情失败: ' + (res.message || '未知错误'));
					}
				} catch (err) {
					uni.hideLoading();
					console.error('调用获取规则详情云对象失败', err);
					this.handleError('网络错误，请重试');
				}
			},
			
			// 从URL获取文件名
			getFileNameFromUrl(url) {
				if (!url) return '';
				const parts = url.split('/');
				const lastPart = parts[parts.length - 1];
				const fileNameParts = lastPart.split('?');
				return decodeURIComponent(fileNameParts[0]);
			},
			
			// 处理错误
			handleError(message) {
				uni.showModal({
					title: '提示',
					content: message,
					showCancel: false,
					success: (res) => {
						if (message.includes('无权') || message.includes('未指定')) {
							uni.navigateBack();
						}
					}
				});
			},
			
			// 分类选择变化
			bindCategoryChange(e) {
				this.categoryIndex = e.detail.value;
				this.formData.category = this.categoryOptions[this.categoryIndex];
			},
			
			// 语言选择变化
			bindLanguageChange(e) {
				this.languageIndex = e.detail.value;
				this.formData.language = this.languageIndex === 0 ? 'zh-CN' : 'en';
			},
			
			// 状态选择变化
			bindStatusChange(e) {
				this.statusIndex = e.detail.value;
				this.formData.status = this.statusIndex === 0 ? 'published' : 'draft';
			},
			
			// 选择文档
			chooseDocument() {
				// 仅支持微信小程序和APP
				// #ifdef MP-WEIXIN || APP-PLUS
				uni.chooseMessageFile({
					count: 1,
					type: 'file',
					extension: ['.pdf', '.doc', '.docx'],
					success: (res) => {
						const tempFile = res.tempFiles[0];
						console.log('选择的文件:', tempFile);
						
						// 检查文件大小限制 (10MB)
						if(tempFile.size > 10 * 1024 * 1024) {
							uni.showToast({
								title: '文件大小不能超过10MB',
								icon: 'none'
							});
							return;
						}
						
						this.documentName = tempFile.name;
						this.uploadFile(tempFile, 'document');
					}
				});
				// #endif
				
				// #ifdef H5
				// 创建一个文件输入元素
				const input = document.createElement('input');
				input.type = 'file';
				input.accept = '.pdf,.doc,.docx';
				
				input.onchange = (event) => {
					const file = event.target.files[0];
					if (!file) return;
					
					// 检查文件大小限制 (10MB)
					if(file.size > 10 * 1024 * 1024) {
						uni.showToast({
							title: '文件大小不能超过10MB',
							icon: 'none'
						});
						return;
					}
					
					this.documentName = file.name;
					
					// 转换为uni-app支持的格式
					const tempFile = {
						path: URL.createObjectURL(file),
						name: file.name,
						size: file.size,
						type: file.type,
						file: file  // 保存原始文件对象，H5环境需要
					};
					
					this.uploadFile(tempFile, 'document');
				};
				
				input.click();
				// #endif
			},
			
			// 选择图片
			chooseImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFile = {
							path: res.tempFilePaths[0],
							size: res.tempFiles[0].size,
							name: this.getFileNameFromPath(res.tempFilePaths[0])
						};
						
						// 检查文件大小限制 (5MB)
						if(tempFile.size > 5 * 1024 * 1024) {
							uni.showToast({
								title: '图片大小不能超过5MB',
								icon: 'none'
							});
							return;
						}
						
						this.uploadFile(tempFile, 'image');
					}
				});
			},
			
			// 从路径获取文件名
			getFileNameFromPath(path) {
				if (!path) return '';
				const parts = path.split('/');
				return parts[parts.length - 1];
			},
			
			// 上传文件到服务器
			uploadFile(tempFile, type) {
				uni.showLoading({
					title: '上传中...'
				});
				
				this.uploadStatus[type] = true;
				
				// 获取上传凭证
				uniCloud.callFunction({
					name: 'getOSSUploadToken',
					data: {},
					success: (tokenRes) => {
						if (tokenRes.result.code === 0) {
							const uploadToken = tokenRes.result.data;
							const filePath = tempFile.path;
							const fileName = tempFile.name || this.getFileNameFromPath(filePath);
							
							// 为文件名添加时间戳，避免重名
							const timestamp = new Date().getTime();
							const fileExt = fileName.split('.').pop();
							const newFileName = `${type}_${this.userId}_${timestamp}.${fileExt}`;
							
							// 计算上传路径
							const uploadDir = type === 'document' ? 'documents/' : 'images/';
							const key = `${uploadDir}${newFileName}`;
							
							// 执行上传
							uni.uploadFile({
								url: uploadToken.upload_host,
								filePath: filePath,
								name: 'file',
								formData: {
									key: key,
									policy: uploadToken.policy,
									OSSAccessKeyId: uploadToken.accessid,
									signature: uploadToken.signature,
									success_action_status: '200'
								},
								success: (uploadRes) => {
									console.log('上传成功:', uploadRes);
									
									// 构建文件访问URL
									const fileUrl = `${uploadToken.host}/${key}`;
									
									// 更新表单数据
									if (type === 'document') {
										this.formData.document_url = fileUrl;
									} else {
										this.formData.image_url = fileUrl;
									}
									
									uni.hideLoading();
									uni.showToast({
										title: '上传成功',
										icon: 'success'
									});
								},
								fail: (err) => {
									console.error('上传失败:', err);
									uni.hideLoading();
									uni.showToast({
										title: '上传失败，请重试',
										icon: 'none'
									});
									this.uploadStatus[type] = false;
								}
							});
						} else {
							uni.hideLoading();
							uni.showToast({
								title: '获取上传凭证失败',
								icon: 'none'
							});
							this.uploadStatus[type] = false;
						}
					},
					fail: (err) => {
						console.error('获取上传凭证失败:', err);
						uni.hideLoading();
						uni.showToast({
							title: '网络错误，请重试',
							icon: 'none'
						});
						this.uploadStatus[type] = false;
					}
				});
			},
			
			// 预览文档
			previewDocument() {
				if (!this.formData.document_url) {
					uni.showToast({
						title: '没有可预览的文档',
						icon: 'none'
					});
					return;
				}
				
				// #ifdef H5
				window.open(this.formData.document_url, '_blank');
				// #endif
				
				// #ifdef MP-WEIXIN || APP-PLUS
				uni.downloadFile({
					url: this.formData.document_url,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.openDocument({
								filePath: res.tempFilePath,
								showMenu: true,
								success: () => {
									console.log('打开文档成功');
								},
								fail: (err) => {
									console.error('打开文档失败:', err);
									uni.showToast({
										title: '打开文档失败',
										icon: 'none'
									});
								}
							});
						}
					},
					fail: (err) => {
						console.error('下载文档失败:', err);
						uni.showToast({
							title: '下载文档失败',
							icon: 'none'
						});
					}
				});
				// #endif
			},
			
			// 预览图片
			previewImage() {
				if (!this.formData.image_url) {
					uni.showToast({
						title: '没有可预览的图片',
						icon: 'none'
					});
					return;
				}
				
				uni.previewImage({
					urls: [this.formData.image_url],
					current: 0
				});
			},
			
			// 删除文档
			removeDocument() {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除当前文档吗？',
					success: (res) => {
						if (res.confirm) {
							this.formData.document_url = '';
							this.documentName = '';
							uni.showToast({
								title: '文档已删除',
								icon: 'success'
							});
						}
					}
				});
			},
			
			// 删除图片
			removeImage() {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除当前图片吗？',
					success: (res) => {
						if (res.confirm) {
							this.formData.image_url = '';
							uni.showToast({
								title: '图片已删除',
								icon: 'success'
							});
						}
					}
				});
			},
			
			// 校验表单
			validateForm() {
				if (!this.formData.title.trim()) {
					uni.showToast({
						title: '请输入规则标题',
						icon: 'none'
					});
					return false;
				}
				
				if (!this.formData.content.trim()) {
					uni.showToast({
						title: '请输入规则内容',
						icon: 'none'
					});
					return false;
				}
				
				if (!this.formData.summary.trim()) {
					uni.showToast({
						title: '请输入规则摘要',
						icon: 'none'
					});
					return false;
				}
				
				if (!this.formData.version.trim()) {
					uni.showToast({
						title: '请输入规则版本',
						icon: 'none'
					});
					return false;
				}
				
				return true;
			},
			
			// 提交表单
			async submitForm() {
				if (!this.validateForm()) {
					return;
				}
				
				this.submitting = true;
				uni.showLoading({
					title: '更新中...'
				});
				
				try {
					// 处理标签，将字符串转换成数组
					let tags = this.formData.tags;
					if (typeof tags === 'string') {
						tags = tags.split(',').map(tag => tag.trim()).filter(tag => tag);
					}
					
					// 构建请求参数
					const updateData = {
						id: this.ruleId,
						title: this.formData.title,
						content: this.formData.content,
						summary: this.formData.summary,
						category: this.formData.category,
						tags: tags,
						version: this.formData.version,
						language: this.formData.language,
						document_url: this.formData.document_url,
						image_url: this.formData.image_url,
						status: this.formData.status,
						updated_at: new Date(),
						creator_id: this.userId
					};
					
					console.log('更新规则数据:', updateData);
					
					// 调用云对象更新规则
					const learningService = uniCloud.importObject('learning-service');
					const res = await learningService.updateRuleContent(updateData);
					
					this.submitting = false;
					uni.hideLoading();
					
					if (res.code === 0) {
						uni.showToast({
							title: '更新成功',
							icon: 'success'
						});
						
						// 延迟返回
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						uni.showModal({
							title: '更新失败',
							content: res.message || '未知错误',
							showCancel: false
						});
					}
				} catch (err) {
					this.submitting = false;
					uni.hideLoading();
					console.error('调用更新规则云对象失败:', err);
					
					uni.showModal({
						title: '更新失败',
						content: '网络错误，请重试',
						showCancel: false
					});
				}
			}
		}
	}
</script>

<style>
	@import "../admin/app.css";
	
	.upload-container {
		margin-bottom: 20rpx;
	}
	
	.upload-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 150rpx;
		background-color: #f5f5f5;
		border: 2rpx dashed #ddd;
		border-radius: 8rpx;
		margin-bottom: 10rpx;
	}
	
	.upload-icon {
		font-size: 40rpx;
		margin-bottom: 10rpx;
	}
	
	.upload-text {
		font-size: 24rpx;
		color: #666;
	}
	
	.upload-tip {
		font-size: 22rpx;
		color: #999;
		margin-top: 6rpx;
	}
	
	.upload-button {
		font-size: 24rpx;
		height: 60rpx;
		line-height: 60rpx;
		margin: 10rpx 0;
		background-color: #1BAE76;
	}
	
	.upload-preview, .image-preview {
		background-color: #f9f9f9;
		padding: 20rpx;
		border-radius: 8rpx;
		margin-bottom: 10rpx;
	}
	
	.preview-name {
		font-size: 26rpx;
		color: #333;
		word-break: break-all;
	}
	
	.preview-actions, .image-actions {
		display: flex;
		margin-top: 10rpx;
	}
	
	.preview-btn, .image-btn {
		flex: 1;
		font-size: 24rpx;
		height: 60rpx;
		line-height: 60rpx;
		margin: 0 10rpx;
	}
	
	.play-btn {
		background-color: #1890ff;
		color: white;
	}
	
	.delete-btn {
		background-color: #ff4d4f;
		color: white;
	}
	
	.preview-image {
		width: 100%;
		height: 300rpx;
		border-radius: 4rpx;
	}
</style> 